/*
 * timer.cpp
 *
 *  Created on: 2016年3月2日
 *      Author: Administrator
 */

#include "timer.h"
#include "thread/single/service.h"

namespace eyas {
namespace process {
timer::~timer() {
	if(enable_){
		{
			boost::recursive_mutex::scoped_lock lck(this->mutex_);
			enable_ = false;
		}
		this->timer_.cancel();
		this->timer_.wait();
	}
	this->release();
}
void timer::release(){
	if(nullptr != this->taskPtr_){
		this->taskPtr_ = nullptr;
	}
}
void timer::schedule_timer_task_from_constructor(eyas::thread::thread_task_ptr& taskPtr){
	enable_ = true;
	this->release();
	this->taskPtr_ = taskPtr;
}
void timer::schedule_timer_task(eyas::thread::thread_task_ptr& taskPtr){
	boost::recursive_mutex::scoped_lock lck(this->mutex_);
	schedule_timer_task_from_constructor(taskPtr);
	this->timer_.expires_from_now(boost::posix_time::milliseconds(this->delay_));
	this->timer_.async_wait(boost::bind(&timer::on_timer, this->shared_from_this()));
}
void timer::on_timer(){
	if(!enable_){
		return;
	}
	eyas::thread::thread_task_ptr taskPtr = this->taskPtr_;
	if(nullptr != taskPtr){
		taskPtr->on_task();
		taskPtr = nullptr;
	}
	boost::recursive_mutex::scoped_lock lck(this->mutex_);
	if(!enable_){
		return;
	}
	if(this->period_ > 0){
		this->timer_.expires_from_now(boost::posix_time::milliseconds(this->period_));
		this->timer_.async_wait(boost::bind(&timer::on_timer, this->shared_from_this()));
	}else{
		this->taskPtr_ = NULL;
		enable_ = false;
	}
}
void timer::start(int delay){
	this->start(delay, 0);
}
void timer::start(int delay, int period){
	boost::recursive_mutex::scoped_lock lck(this->mutex_);
	this->delay_ = delay;
	this->period_ = period;
	enable_ = true;
	this->timer_.expires_from_now(boost::posix_time::milliseconds(this->delay_));
	this->timer_.async_wait(boost::bind(&timer::on_timer, this->shared_from_this()));
}
void timer::cancel(){
	boost::recursive_mutex::scoped_lock lck(this->mutex_);
	enable_ = false;
	this->timer_.cancel();
}

} /* namespace timer */
} /* namespace eyas */
